#-*-coding:utf8;-*-
from matplotlib.pyplot import savefig
from numpy import flatiter, left_shift, nan
from numpy.lib.function_base import append
import pandas as pd
import time
import numpy as np
import mplfinance as mpf
import os
import tushare as ts
# from  chinese_calendar  import is_holiday
import datetime
from ylTDX import * #from ylTDX import all def function

pd.options.mode.chained_assignment = None #avoid :pandas SettingWithCopyWarning
ts.set_token("6667cd4a2326f2f937062a0f4fb59aea5c56d13b1f6f26225f115fe9")
"""
LC:=REF(CLOSE,1);
抄:SMA(MAX(CLOSE-LC,0),12,1)/SMA(ABS(CLOSE-LC),12,1)*100 LINETHICK2;
底:30 COLORRED LINETHICK3;
神:70 COLORGREEN LINETHICK3;
针:50  COLORYELLOW LINETHICK3;
"""


def ChaoDiShenZhen(file_name,code):                      
    days=60
    Today=time.strftime("%Y-%m-%d-%H-%M-%S")
    year=int(Today.split('-')[0])
    month=int(Today.split('-')[1])
    pro = ts.pro_api()
    end_date_str=time.strftime("%Y%m%d")
    end_datetime = datetime.datetime.strptime(end_date_str, '%Y%m%d') 
    start_datetime=n_days_before(end_datetime,days)
    start_date_str=start_datetime.strftime("%Y%m%d")
    try:
        df = pro.daily(ts_code='{}.SZ'.format(str(code).zfill(6)), start_date=start_date_str, end_date=end_date_str)       
    except Exception as e:
        print(e)
        time.sleep(60) 
        df = pro.daily(ts_code='{}.SZ'.format(str(code).zfill(6)), start_date=start_date_str, end_date=end_date_str)
    df.set_index('trade_date',inplace=True)
    df.sort_index(inplace=True)   
    df.rename(columns={'vol': 'volume'},inplace=True)  
    df_new=df[["open","high","low","close","volume","amount"]]
    OPEN=df_new["open"].to_list() #open 是file open
    HIGH=df_new["high"].to_list()
    LOW=df_new["low"].to_list()
    CLOSE=df_new["close"].to_list()  
    VOLUME=df_new["volume"].to_list() 
    AMOUNT=df_new["amount"].to_list() 
    LC=REF(CLOSE,1)
    抄=multiply(divide(SMA(MAX(subtraction(CLOSE,LC),0),12,1),SMA(ABS(subtraction(CLOSE,LC)),12,1)),100)
    底=30
    神=70
    针=50
    output_File = open(file_name,'a+') 
    if len(抄)>0:
        output_File.write('{},{},{}\n'.format(str(code).zfill(6),str(round(抄[-1],2)),df_new['close'][-1]))
        output_File.flush()
    else:
        output_File.flush()
    return "%s complete"%str(code).zfill(6)


def multi_thread_chao_di_check(file_name,code_list):
    """
    使用线程池，由系统自动分配线程数量，并打印线程目标函数的返回结果
    """  
    #在append之前先删除原数据表
    import concurrent.futures
    with concurrent.futures.ThreadPoolExecutor() as executor:     
        results=[ executor.submit(ChaoDiShenZhen,file_name,i) for i in code_list]
        for f in concurrent.futures.as_completed(results):
            print(f.result())      

if __name__=='__main__':
    path=os.getcwd()
    # df=pd.read_csv(path+'/after_process.csv')
    # df1=df[["code",'f10']]
    # df1.query('f10==True',inplace=True)
    # df1.drop(columns=['f10'],inplace=True)
    # df1.to_csv("f10_true.csv")
    df1=pd.read_csv(path+'/f10_true.csv')
    code_index_list=df1['code'].to_list()
    # file_name="{}.csv".format("chao_di_shen_zhen"+str(time.strftime("%Y_%m_%d_%H")))
    file_name="cdsz.csv"
    if os.path.exists(file_name): os.remove(file_name)
    output_File = open(file_name,'a+')
    output_File.write('{},{},{}\n'.format('code','cdsz','close'))
    output_File.flush()
    multi_thread_chao_di_check(file_name,code_index_list)  
    #zljc由大到小排序
    df_res=pd.read_csv(file_name,encoding='unicode_escape') 
    df_res.columns=['code','cdsz','close']
    df_res.sort_values(by='cdsz',ascending=True,inplace=True)
    df_res.to_csv(file_name)
